import { Body, Controller, Delete, Get, Param, Post, Put, UsePipes } from '@nestjs/common';
import { isNumber } from 'class-validator';
import { RechargeOptionModelService } from 'src/model/recharge-option-model/recharge-option-model.service';
import dtoValidationPipe from 'src/pipe/Dto.pipe';
import { errorReturn, successReturn } from 'src/utils';
import { AddDto, EditDto } from './dto';

@Controller('recharge')
export class RechargeController {
    constructor(
        private rechargeOptionModelService:RechargeOptionModelService
    ){}

    @Get('options')
    async options() {
        const options = await this.rechargeOptionModelService.find()
        console.log(options)
        return successReturn(options)
    }

    @Post('addOption')
    @UsePipes(dtoValidationPipe())
    async addOption(@Body() dto:AddDto) {
       try {
            let data:any = {
                amount : dto.amount
            }
            if('payAmount' in dto) {
                data.payAmount = dto.payAmount
            }
            const id = await this.rechargeOptionModelService.insert(data)
            return id ? successReturn('保存成功', {data : id}) : errorReturn('保存失败')
       } catch (error) {
           return errorReturn(error.message)
       }
    }

    @Put('editOption/:id')
    @UsePipes(dtoValidationPipe({skipMissingProperties : true}))
    async editOption(@Param('id') id:number, @Body() dto:EditDto) {
        id = Number(id)
        if(!isNumber(id) || id <= 0) return errorReturn()
        const res = await this.rechargeOptionModelService.update({id : id}, dto)

        return successReturn()
    }

    @Delete('deleteOption/:id')
    async deleteOption(@Param('id') id:number) {
        id = Number(id)
        if(!isNumber(id) || id <= 0) return errorReturn()
        const res = await this.rechargeOptionModelService.delete(id)
        return successReturn()
    }
}
